﻿using MapsterMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NLog;
using WoodAdmin.Common.Extention;
using WoodAdmin.Common.Helper;
using WoodAdmin.Common.Helper.Log;
using WoodAdmin.Models;
using WoodAdmin.Models.ViewModels;
using WoodAdmin.Services;
using System;
using System.Linq;

namespace WoodAdmin.Controllers.Api
{
    [AllowAnonymous]
    public class PublicController:BaseApiController
    {
        private readonly UserInfoService _service;
        private readonly IMapper _mapper;

        public PublicController(UserInfoService service, IMapper mapper)
        {
            _service = service;
            _mapper = mapper;
        }
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="register"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultViewModel Register(Register register)
        {
            #region 验证信息
            if (_service.Queryable(a => a.Email.Equals(register.Email)).Any())
            {
                return JsonError("该邮箱已被占用！");
            }
            if (_service.Queryable(a => a.Phone.Equals(register.Phone)).Any())
            {
                return JsonError("该手机号已被占用！");
            }
            
            //RSA解密前台传入的密码
            //var rsa = new RSAHelper(RSAType.RSA, Encoding.UTF8, APPKeys.PrivateKey, APPKeys.PublicKey);
            //register.Password = rsa.Decrypt(register.Password);
            #endregion

            register.Password = register.Password.ToMD5String();
            var dbUserInfo = _mapper.Map<UserInfo>(register);
            dbUserInfo.CreateTime = DateTime.Now;
            if (_service.Insert(dbUserInfo))
            {
                return JsonSuccess("注册成功！");
            }
            return JsonError("用户注册失败！");
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="model">用户登录数据模型</param>
        /// <returns></returns>
        [HttpPost]
        public ResultViewModel Login(LoginModel model)
        {
            //RSA解密前台传入的密码
            //var rsa = new RSAHelper(RSAType.RSA, Encoding.UTF8, APPKeys.PrivateKey, APPKeys.PublicKey);
            //model.Password = rsa.Decrypt(model.Password);

            var userInfoList = _service.Queryable(a => a.Email.Equals(model.Email.Trim()) && a.Password.Equals(model.Password.Trim().ToMD5String())).ToList();
            if (userInfoList.Any())
            {
                var DbUserInfo = userInfoList.FirstOrDefault();
                NLogger.Info($"用户{DbUserInfo.UserName}在{DateTime.Now.ToShortTimeString()}登录了");
                return JsonSuccess("Success", new LoginResultModel() { Token = JwTHelper.GetJWT(DbUserInfo), UserInfo = DbUserInfo });
            }
            return JsonError("用户名或密码错误！");
        }
    }
}
